package com.yu.discovery;

import com.yu.factory.SingletonFactory;
import com.yu.loadBalance.LoadBalance;
import com.yu.loadBalance.RandomLoadBalance;
import com.yu.util.CuratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @PackageName: com.yu.discovery
 * @Description: 发现在zk上的服务
 * @Version: v1.0.0
 * @Author: yuweilin
 * @Date: 21:32
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ------------------------------------------------------------
 * 2021/2/5      yuweilin         v1.0.0               新建
 */
@Slf4j
public class ZKServiceDiscovery implements ServiceDiscovery{
    //负载均衡策略
    private final LoadBalance loadBalance;

    public ZKServiceDiscovery() {
        loadBalance = SingletonFactory.getInstance(RandomLoadBalance.class);
    }

    @Override
    public InetSocketAddress lookupService(String rpcServiceName) {
        CuratorFramework client = CuratorUtil.getZkClient();
        List<String> childrenNodes = CuratorUtil.getChildrenNodes(client, rpcServiceName);
        if (childrenNodes==null||childrenNodes.size()==0){
            throw new RuntimeException("没有发现该服务");
        }
        String address = loadBalance.selectServiceAddress(childrenNodes);
        log.info("使用随机分配的策略发现地址：{}",address);
        String[] hostAndPort = address.split(":");
        String host = hostAndPort[0];
        int port = Integer.parseInt(hostAndPort[1]);
        return new InetSocketAddress(host, port);
    }
}
